<template>
  <div class="departments">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>组织结构</span>
      </div>
      <div class="text item schema">
        <!-- 组织结构内部顶部栏 -->
        <treeitem :item="treetop" :istop="true" />
        <hr>
        <!-- 数据结构内容 -->
        <el-tree :data="treedata" :props="{ label: 'name' }" default-expand-all>
          <template v-slot="{ data }">
            <treeitem
              style="width: 100%"
              :item="data"
              @getData="getDepartmentsInfo"
            />
          </template>
        </el-tree>
        <!-- 弹框 -->
        <popout :init-list="initList" @getData="getDepartmentsInfo" />
      </div>
    </el-card>
  </div>
</template>

<script>
import treeitem from './components/treeitem.vue'
import { companyDepartment } from '@/api/departments.js'
import Popout from './components/popout.vue'

export default {
  components: {
    treeitem,
    Popout
  },

  data() {
    return {
      treetop: {
        name: '',
        manager: '负责人',
        id: ''
      },
      treedata: [],
      // 获取到的原始数据
      initList: []
    }
  },

  created() {
    this.getDepartmentsInfo()
  },

  methods: {
    async getDepartmentsInfo() {
      const res = await companyDepartment()
      this.treetop.name = res.data.companyName
      this.initList = res.data.depts
      this.treedata = this.changeData(res.data.depts, '')
    },
    changeData(arr, pid = '') {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 15px;
  .box-card {
    padding: 30px;
    font-size: 14px;
  }
  .schema {
    padding: 30px;
  }
}
</style>
